import { clusterLayerStyleMap } from '../cluster-layer-style'

export default {
  methods: {
    /**
     * api 调用 MapUtils 内的方法
     */
    invokeUtils (methodName, ...args) {
      if (!this.map1) return
      return this.map1.mapUtil[methodName](...args)
    },
    invokeMap2Utils (methodName, ...args) {
      if (!this.map2) return
      return this.map2.mapUtil[methodName](...args)
    },
    /**
     * api feature 数据转换
     */
    transfromFeature (data, toFeature = true) {
      if (!toFeature && data.getGeometry().getType() === 'Circle') {
        return null
      }
      if (this.mapDataType === 'wkt') {
        return this.map1.bkol[toFeature ? 'wkt2feature' : 'feature2Wkt'](data)
      } else if (this.mapDataType === 'geojson') {
        return this.map1.bkol[toFeature ? 'geoJson2feature' : 'feature2GeoJson'](data)
      }
    },
    /**
     * api 切换模式：卷帘（-1）、全图（1）、双图（2）、切换（3）
     */
    switchMapMode (mapMode, compareLayers = []) {
      if (!this.map1) return
      const mode = Number(mapMode)
      this.compare = mode === 2
      this.isSwitchMapMode = false
      // 卷帘模式下 compareLayers 必传
      if (mode === -1) {
        this.compareLayers = compareLayers
        this.map1.mapUtil.onPointerMove(compareLayers.join(','))
      } else {
        if (this?.compareLayers?.length) {
          this.map1.mapUtil.unPointerMove(this.compareLayers.join(','))
          this.compareLayers = []
        } else {
          this.map1.mapUtil.unPointerMove('')
        }
        if (mode === 3) {
          this.isSwitchMapMode = true
          if (this.switchLayers?.length) {
            this.setLayerVisible(this.switchLayers.join(','), false)
          }
          if (compareLayers.length) {
            this.switchLayers = compareLayers
            this.setLayerVisible(compareLayers.join(','), true)
          } else {
            this.switchLayers = []
          }
        }
      }
    },
    /**
     * api 切换图层显示与隐藏
     */
    setLayerVisible (layerIds, visible, map = 'map1') {
      const layerArr = layerIds.split(',')
      for (const id of layerArr) {
        if (!id) continue
        const layer = this[map].mapUtil.getLayer(id)
        if (layer) {
          if (layer.get('hasCluster')) {
            this[map].mapUtil.changeLayer(id + '_cluster', visible)
            this[map].mapUtil.changeLayer(id, visible)
          } else {
            this[map].mapUtil.changeLayer(id, visible)
          }
        }
      }
    },
    /**
     * api 开启编辑操作
     */
    startModify (feature, callback, eventKey) {
      if (feature) {
        const layer = this.map1.mapUtil.getLayer('modifylayer')
        const newFeature = feature.clone()
        // newFeature.setStyle(this.map1.mapUtil.getPointEditStyle())
        layer.getSource().addFeature(newFeature)
      }
      if (this.undoRedoInteraction) {
        this.undoRedoInteraction.clear()
      } else {
        this.undoRedoInteraction = this.map1.mapUtil.createUndoRedo({ layers: ['modifylayer'] })
      }
      this.modifyInteraction = this.map1.mapUtil.createModify('modifylayer', {
        modifyend: (event) => {
          if (eventKey) {
            this.drawEventKey = eventKey
          }
          if (callback) {
            callback(event)
          }
        }
      })
      return this.modifyInteraction
    },
    startModifyByOptions (options) {
      const { feature = null, callback = null, eventKey = '' } = options
      this.startModify(feature, callback, eventKey)
    },
    /**
     * api 开启圈画操作
     */
    startDraw (callback, type = 'Polygon', extra, eventKey) {
      this.drawMultiple = type.startsWith('Multi')
      this.drawInteraction = this.map1.mapUtil.createDraw('modifylayer', type, {
        drawend: (event) => {
          if (eventKey) {
            this.drawEventKey = eventKey
          }
          if (this.drawMultiple) return
          this.drawInteraction.setActive(false)
          this.startModify()
          if (type === 'Circle') {
            event.feature.setStyle(this.map1.mapUtil.getPointEditStyle())
          }
          if (callback) {
            callback(event, this.transfromFeature(event.feature, false))
          }
        }
      }, extra)
      return this.drawInteraction
    },
    startDrawByOptions (options) {
      const { callback = null, type = 'Polygon', extra = null, eventKey = '' } = options
      this.startDraw(callback, type, extra, eventKey)
    },
    /**
     * api 显示工具栏
     */
    showTool (data) {
      this.toolVisible = true
      if (this.isGlobal) {
        this.$store.commit('settings/setLayoutVisible', false)
      }
      this.originModifyWKT = data || ''
    },
    /**
     * api 获取所有图层数据，包括基础图层和动态添加的图层
     */
    getAllLayers (map = 'map1') {
      return this[map].layerManager.layersarr
    },
    /**
     * api 清空指定的地图图层
     */
    clearLayers (layers = 'modifylayer', map = 'map1') {
      if (this[map]) {
        const layerList = Array.isArray(layers) ? layers : [layers]
        for (const id of layerList) {
          const layer = this[map].mapUtil.getLayer(id)
          if (layer) {
            layer.getSource().clear()
          }
        }
      }
    },
    /**
     * api 移除基础图层外的所有图层
     */
    resetAllLayers (map = 'map1') {
      const layers = (this[map]?.layerManager?.getAllLayer() ?? [])
        .filter(l => !this.oriLayers.includes(l))
      if (layers.length) {
        this[map].mapUtil.removeLayer(layers.join(','))
      }
      this.closePopup()
      this.mapSingleClickInteraction = null
      this.mapPointMoveInteraction = null
    },
    /**
     * api 打开地图浮层
     */
    openPopup (coordinate, html) {
      if (this.map1?.popup && !this.popupDisabled) {
        this.map1.popup.show(coordinate, html)
      }
    },
    /**
     * api 打开地图提示浮层
     */
    openTipsPopup (coordinate, html) {
      if (this.map1?.tipsPopup) {
        this.map1.tipsPopup.show(coordinate, html)
      }
    },
    /**
     * api 关闭地图浮层
     */
    closePopup () {
      if (this.map1?.popup) {
        this.map1.popup.hide()
      }
    },
    /**
     * api 设置地图中心点和缩放
     */
    setCenterAndZoom (center, zoom = 14, animate = true) {
      if (!center[0] || !center[1]) {
        this.$message.warning('经纬度为空，无法定位')
        return false
      }
      if (animate) {
        this.map1.getView().animate({ center, zoom, duration: 500 })
      } else {
        this.map1.getView().setCenter(center)
        this.map1.getView().setZoom(zoom)
      }
      this.$store.commit('map/setZoom', zoom)
    },
    /**
     * api 指定位置自适应显示
     */
    fit (extent, options, map = 'map1') {
      options = { ...{ duration: 500, maxZoom: 13, padding: [50, 50, 50, 50] }, ...options }
      setTimeout(() => {
        this[map].getView().fit(extent, options)
        setTimeout(() => {
          this.$store.commit('map/setZoom', this[map].getView().getZoom())
        }, options.duration + 200)
      }, 200)
    },
    /**
     * api 打开遮罩图层
     */
    openMaskLayer (data, needFit = true, fitOptions, map = 'map1') {
      const feature = this.transfromFeature(data, true)
      if (map === 'map1') {
        this.maskGeometry = feature.getGeometry()
      }
      setTimeout(() => {
        // 定位到当前位置
        if (needFit) {
          this.fit(feature.getGeometry(), fitOptions)
        }
        const layer = this[map].mapUtil.getLayer('zhezhaolayer')
        layer && layer.getSource().clear()
        const extent = window.turf.bboxPolygon([-180, -90, 180, 90])
        const json = this[map].bkol.feature2GeoJson(feature)
        const resultFeature = this[map].bkol.geoJson2feature(window.turf.difference(extent, json))
        layer.getSource().addFeature(resultFeature)
      }, 500)
    },

    /**
     * api 关闭遮罩图层
     */
    closeMaskLayer (map = 'map1') {
      if (this?.[map]?.mapUtil) {
        const layer = this[map].mapUtil.getLayer('zhezhaolayer')
        layer && layer.getSource().clear()
      }
    },
    /**
     * api 增加图层
     */
    async addLayers (configs, map = 'map1') {
      return new Promise((resolve, reject) => {
        if (!this[map]) {
          resolve([])
        }
        // 获取已存在的图层
        const allLayerIds = this[map]?.layerManager?.getAllLayer() ?? []
        const newLayers = []
        const newLayerIds = []
        for (let i = 0; i < configs.length; i++) {
          const c = configs[i]
          newLayerIds.push({
            id: c.bklayerId,
            hasCluster: c.needCluster || false,
            hasText: c.hasText || false,
            textKey: c.textKey,
            isClick: c.isClick,
            isHover: c.isHover
          })
          if (allLayerIds.includes(c.bklayerId)) {
            // 判断是否有重复图层  若是重复 设置显隐属性即可
            this.setLayerVisible(c.bklayerId, c.visible, map)
            // 判断是否为聚合图层
            if (c.needCluster) {
              this.setLayerVisible(c.bklayerId + '_cluster', c.visible, map)
            }
          } else {
            // 判断是否为聚合图层
            if (c.needCluster) {
              newLayers.push(
                {
                  // 图层业务分组标识
                  bklayerGroupId: c?.bklayerGroupId,
                  // 图层唯一标识
                  bklayerId: c?.bklayerId,
                  // 图层层级，不能重复
                  bklayerSn: c?.bklayerSn ?? (50 + i + 1),
                  // 图层类型，LayerCreator 中固定的几类
                  bklayerType: 'vectorlayer_empty',
                  bklayerName: c?.bklayerName || '行政区划',
                  visible: c?.visible ?? true,
                  isHidden: false,
                  maxResolution: this.map1.bkjson.map.GlobalCfg.showResolution
                },
                {
                // 图层业务分组标识
                  bklayerGroupId: c?.bklayerGroupId,
                  // 图层唯一标识
                  bklayerId: c?.bklayerId + '_cluster',
                  // 图层层级，不能重复
                  bklayerSn: c?.clusterSn,
                  // 图层类型，LayerCreator 中固定的几类
                  bklayerType: 'clusterlayer',
                  bklayerName: c?.bklayerName || '行政区划',
                  visible: c?.visible ?? true,
                  isHidden: false,
                  minResolution: this.map1.bkjson.map.GlobalCfg.showResolution,
                  distance: this.map1.bkjson.map.GlobalCfg.cluster_distance
                })
            } else {
              const props = c.props || {}
              newLayers.push({
                // 图层业务分组标识
                bklayerGroupId: c?.bklayerGroupId,
                // 图层唯一标识
                bklayerId: c?.bklayerId,
                // 图层层级，不能重复
                bklayerSn: c?.bklayerSn ?? (50 + i + 1),
                // 图层类型，LayerCreator 中固定的几类
                bklayerType: c?.bklayerType,
                bklayerName: c?.bklayerName || '行政区划',
                bklayerUrl: c?.bklayerUrl || '',
                visible: c?.visible ?? true,
                isHidden: false,
                bklayers: c?.bklayers || '',
                singleTile: c?.singleTile || false,
                bkstyle: c.bkstyle,
                extent: c.extent,
                declutter: c.declutter ?? false,
                ...props
              })
            }
          }
        }
        // 如果新加了图层
        if (newLayers.length) {
          // 层级错误处理
          const zIndexList = newLayers.map(item => item.bklayerSn)
          if (Array.from(new Set(zIndexList)).length < zIndexList.length) {
            console.error('本次新增数组有重复的层级，可能会影响地图渲染')
          }

          const cfs = [{
            groupId: 'baseInfolayers',
            expand: true,
            text: '基础地理信息图层',
            mulSel: true,
            isHidden: false,
            layers: newLayers
          }]
          this[map].layerManager.addLayers(cfs)
          for (const l of newLayers) {
            if (!this.mapSingleClickInteraction) {
              this.mapSingleClickInteraction = this.map1.mapUtil.createMapEvent(l.bklayerId, 'singleclick', this.selectStyle, this.selectFilter)
              this.mapSingleClickInteraction.on('select', this.selectedCallback)
            }
            if (!this.mapPointMoveInteraction) {
              this.mapPointMoveInteraction = this.map1.mapUtil.createMapEvent(l.bklayerId, 'pointermove', this.selectStyle, this.selectFilterByfilter)
              this.mapPointMoveInteraction.on('select', this.moveCallback)
            }
          }
        }
        const layers = newLayerIds.map(({ id, hasCluster, hasText, textKey, isClick, isHover }) => {
          const layer = this[map].mapUtil.getLayer(id)
          layer.set('hasCluster', hasCluster, true)
          // 判断是否有文字需要显示
          layer.set('hasText', hasText, true)
          if (hasText && !textKey) {
            console.warn('图层' + id + '开启了文字显示，但是没有传 textKey')
          }
          layer.set('textKey', textKey, true)
          // 判断图层是否被允许触发点击时间和移入事件
          layer.set('isClick', isClick, true)
          layer.set('isHover', isHover, true)

          this.$store.commit('map/updateLayerZIndex', { layerId: id, zIndex: layer.getZIndex() })
          return layer
        })
        resolve(layers)
        this.emitEvent('updateLayer', newLayerIds)
      })
    },
    /**
     * api 渲染聚合图层，需配合 map-style 文件的样式
     */
    renderClusterLayer (layerId, features) {
      features = Array.isArray(features) ? features : [features]
      // 判断是否存在聚合图层
      const layer = this.map1.mapUtil.getLayer(layerId)
      if (layer) {
        if (!layer.get('hasCluster')) {
          console.error('不存在聚合图层')
          return
        }
      }
      const result = []
      // 这里是聚合图层处理，非聚合图层在外部加入layer
      const layerClusterId = layerId + '_cluster'
      const layerCluster = this.map1.mapUtil.getLayer(layerClusterId)
      for (const feature of features) {
        const geometry = feature.getGeometry()
        let featureClone = null
        // 获取克隆feature
        if (geometry.getType() === 'Point') {
          // 点的处理
          featureClone = feature.clone()
        } else {
          // 矢量图的处理
          const geoJson = this.map1.bkol.geometry2GeoJson(geometry)
          // 获取矢量图的中心点，这个函数需要传空间对象JSON, 返回一个点的feature
          const centroid = window.turf.centroid(geoJson)
          const coordinates = centroid.geometry.coordinates
          const point = this.map.bkol.getPoint(...coordinates)
          featureClone = new window.ol.Feature(point)
        }
        // 聚合图层的样式在外部文件统一管理，可加载缓存，提高性能
        featureClone.set('bklayerStyleObject', clusterLayerStyleMap)
        featureClone.set('bklayerStyleFunction', layerClusterId + '_func')
        result.push(featureClone)
      }
      layerCluster.getSource().getSource().addFeatures(result)
    },
    /**
     * api 设置地图右键菜单,参数是传入一个方法(feature, layerId, event)
     */
    setContextMenuMethod (fn) {
      this.setCurrentContextMenu = fn
    },
    /**
     * api 清空选中的 features
     */
    clearSelectedFeatures (event = this.mapSingleClickInteraction) {
      if (event) {
        event.getFeatures().clear()
      }
    },
    /**
     * api 清空选中的 features的循环样式时间戳
     */
    clearSelectStyle () {
      console.log('clearSelectStyle')
      if (window.mapSelectTimer) {
        clearInterval(window.mapSelectTimer)
        window.mapSelectTimer = null
      }
    },
    /**
     * api 手动选中一个 feature
     */
    selectFeature (feature, isMultiple = false) {
      if (this.mapSingleClickInteraction) {
        if (!isMultiple) {
          this.clearSelectedFeatures(this.mapSingleClickInteraction)
        }
        this.mapSingleClickInteraction.getFeatures().push(feature)
        this.mapSingleClickInteraction.dispatchEvent({ type: 'select', selected: [feature] })
      }
    },
    /**
     * api 手动触发移入事件
     */
    selectFeatureByMove (feature, isMultiple = false) {
      if (this.mapPointMoveInteraction) {
        if (!isMultiple) {
          this.clearSelectedFeatures(this.mapPointMoveInteraction)
        }
        this.mapPointMoveInteraction.getFeatures().push(feature)
        this.mapPointMoveInteraction.dispatchEvent({ type: 'select', selected: [feature] })
      }
    },
    /**
     * api 关闭编辑交互
     */
    closeModify () {
      this.modifyInteraction && this.modifyInteraction.setActive(false)
    },
    /**
     * api 关闭圈画交互
     */
    closeDraw () {
      this.drawInteraction && this.drawInteraction.setActive(false)
    }
  }
}
